﻿using DoNetDrive.Common.Extensions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _8280WEBSocket
{
    public partial class WorkParamForm : frmNodeForm
    {
        // private INMain mMainForm;
        public WorkParamForm(INMain main) : base(main)
        {
            InitializeComponent();
        }
        /// <summary>
        /// 读取工作参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_ReadWorkParam_Click(object sender, EventArgs e)
        {
            var cd = mMainForm.GetCommandDetail();
            cd.CommandCompleteEvent += (s, c) =>
            {
                var result = c.Result as Command.WorkParameter.GetWorkParameterResult;
                mMainForm.AddLog("读取工作参数成功"+result.JsonValue);
            };
            var cmd = new Command.WorkParameter.GetWorkParameter(cd);
            mMainForm.AddCommand(cmd);
        }
        /// <summary>
        /// 写入工作参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_WriteWorkParam_Click(object sender, EventArgs e)
        {
            if (!CheckWorkParameter(out var model))
            {
                return;
            }
            var sJson = model.ToJSON();
            var cd = mMainForm.GetCommandDetail();
            cd.CommandCompleteEvent += (s, c) =>
            {
                var result = c.Result as Command.WorkParameter.SetWorkParameterResult;
                mMainForm.AddLog("写入工作参数成功:" + result.JsonValue);
            };
            var cmd = new Command.WorkParameter.SetWorkParameter(cd, model);
            mMainForm.AddCommand(cmd);
        }

        private bool CheckWorkParameter(out Command.WorkParameter.SetWorkParam_DTO model)
        {
            model = new Command.WorkParameter.SetWorkParam_DTO();
            #region 门禁参数
            model.Cardbytes = GetCardBytes();
            model.ReleaseTime = (ushort)num_releaseTime.Value;
            model.Free = cmbFree.SelectedIndex;
            model.WgOutput = new Models.WgOutputModel
            {
                Use = cmbWgUse.SelectedIndex,
                Bits = GetBits(),
                Order = cmbWgOrder.SelectedIndex + 1,
                Type = cmbWgType.SelectedIndex + 1
            };
            model.Repeat = new Models.RepeatModel
            {
                Use = cmbRepeatUse.SelectedIndex,
                Interval = (short)numRepeatInterval.Value,
                Mode = cmbRepeatMode.SelectedIndex + 1
            };

            #endregion
            #region UI界面
            model.Brightness = cmbBrightness.SelectedIndex + 1;
            model.Exposure = GetExposure();
            model.IR = cmbIR.SelectedIndex;
            model.Name = txtName.Text;
            model.MenuPassword = txtPassword.Text;
            model.QRCodePath = txtQRCodePath.Text;
            model.TimeZone = txtTimeZone.Text;
            #endregion
            #region 人脸识别

            model.Light = cmbLight.SelectedIndex;
            model.Bioassay = cmbBioassay.SelectedIndex;
            model.Distance = cmbDistance.SelectedIndex + 1;
            model.BioassayThreshold = (int)numBioassayThreshold.Value;
            model.FaceMask = cmbFaceMask.SelectedIndex;
            model.FaceMaskThreshold = (int)numMaskThreshold.Value;
            model.BodyTmp = new Command.Models.BodyTmpModel
            {
                Use = cmbBodyTmpUse.SelectedIndex,
                Alarm = cmbOpenTimeoutAlarmAlarm.SelectedIndex,
                Format = cmbBodyTmpFromat.SelectedIndex,
                Show = cmbBodyTmpShow.SelectedIndex
            };

            #endregion

            #region 设备开门时段

            model.TimeGroups = TimeGroup.Select(a => a.Value).ToList();

            #endregion

            #region 系统信息

            model.Door = cmbDoor.SelectedIndex;
            model.Language = cmbLanguage.SelectedIndex + 1;
            model.SavePhoto = cmbSavePhoto.SelectedIndex;
            model.SaveExternalvisitors = cmbSaveExternalvisitors.SelectedIndex;
            if (DateTime.TryParse(txtTime.Text, out var time))
            {
                model.Time = time.ToString("yyyy-MM-dd HH:mm:ss") + " 0" + time.DayOfWeek.ToString("d");
            }
            model.Volume = cmbVolume.SelectedIndex;
            model.VoiceMode = cmbVoiceMode.SelectedIndex;
            model.StrangerVoice = cmbStrangerVoice.SelectedIndex;
            model.Grettings = cmbGrettings.SelectedIndex;
            string sMakerDate = null;
            if (DateTime.TryParse(txtMakerDate.Text, out var makerDate))
            {
                sMakerDate = makerDate.ToDateTimeStr();
            }
            model.Maker = new Models.MakerModel
            {
                Name = txtMakerName.Text,
                Date = sMakerDate,
                Url = txtMakerUrl.Text
            };


            #endregion

            #region 报警参数

            model.OpenTimeoutAlarm = new Models.OpenTimeoutAlarm
            {
                Use = cmbOpenTimeoutAlarmUse.SelectedIndex,
                Alarm = cmbOpenTimeoutAlarmAlarm.SelectedIndex,
                Timeout = (int)NumOpenTimeoutAlarmTimeout.Value
            };
            model.SensorAlarm = new Models.SensorAlarmModel
            {
                Use = cmbSensorAlarmUse.SelectedIndex,
                Time = SensorAlarmWeek
            };
            #endregion
            return true;
        }
        int[] iCardBytes = new int[] { 0, 2, 3, 4, 8 };
        private int GetCardBytes()
        {
            if (cmb_Cardbytes.SelectedIndex > iCardBytes.Length)
            {
                return 0;
            }
            return iCardBytes[cmb_Cardbytes.SelectedIndex];
        }
        int[] iBits = new int[] { 0, 26, 34, 66 };
        private int GetBits()
        {
            if (cmbWgBits.SelectedIndex > iBits.Length)
            {
                return 0;
            }
            return iBits[cmbWgBits.SelectedIndex];
        }
        int[] iExposure = new int[] { -1, -2, -3, 1, 2, 3 };
        private int GetExposure()
        {
            if (cmbExposure.SelectedIndex > iExposure.Length)
            {
                return -1;
            }
            return iExposure[cmbExposure.SelectedIndex];
        }
        /// <summary>
        /// 写入网络参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSetIPPar_Click(object sender, EventArgs e)
        {
            var ip = new Command.Models.IpModel
            {
                Ip = txtIp.Text,
                Mac = txtMac.Text,
                Dhcp = cmbDhcp.SelectedIndex,
                Gateway = txtGateway.Text,
                Mask = txtMask.Text,
                Dns = txtDns.Text,
                Udp = int.Parse(txtUdp.Text),
                Tcp = int.Parse(txtTcp.Text),
                Websocket = int.Parse(txtWebSocket.Text),
                Ssl = cmbSsl.SelectedIndex,
            };
            var websocket = new Command.Models.WebsocketModel
            {
                Server = txtServer.Text,
                Port = int.Parse(txtPort.Text),
                Token = txtToken.Text,
                ServerSSLCert = txtServerSSLCert.Text,
                Status = cmbStatus.SelectedIndex,
                Keepalive = int.Parse(txtKeepalive.Text),
                Keeptime = int.Parse(txtKeeptime.Text),
                ReconnectTime = int.Parse(txtReconnectTime.Text)
            };
            var wifi = new Command.Models.WiFiModel
            {
                Use = cmbWifiUse.SelectedIndex,
                Ip = txtWifiIp.Text,
                Gateway = txtWifiGateway.Text,
                Password = txtWifiPassword.Text,
                Name = txtWifiName.Text,
                Mask = txtWifiMask.Text
            };

            var setIPPar = new Command.IPPar.SetIPPar_DTO()
            {
                Ip = ip,
                Server = websocket,
                WiFi = wifi,
            };
            var sIp = JsonConvert.SerializeObject(new Command.IPPar.GetIPPar_DTO()
            {
                Ip = ip,
                Server = websocket,
                WiFi = wifi,
            }, Formatting.Indented);
            var cd = mMainForm.GetCommandDetail();
            cd.CommandCompleteEvent += (s, c) =>
            {
                var result = c.Result as Command.IPPar.SetIPParResult;
                mMainForm.AddLog("写入网络参数成功:" + Environment.NewLine + ConvertJsonString(result.JsonValue));
            };
            var cmd = new Command.IPPar.SetIPPar(cd, setIPPar);
            mMainForm.AddCommand(cmd);
        }
        /// <summary>
        /// 读取网络参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnGetIPPar_Click(object sender, EventArgs e)
        {
            var cd = mMainForm.GetCommandDetail();
            cd.CommandCompleteEvent += (s, c) =>
            {
                var result = c.Result as Command.IPPar.SetIPParResult;
                mMainForm.AddLog("读取网络参数成功:" + result.JsonValue);
            };
            var cmd = new Command.IPPar.GetIPPar(cd);
            mMainForm.AddCommand(cmd);
        }

        private void WorkParamForm_Load(object sender, EventArgs e)
        {
            cmb_Cardbytes.SelectedIndex = 0;
            num_releaseTime.Value = 3;
            cmbFree.SelectedIndex = 1;
            cmbWgUse.SelectedIndex = 0;
            cmbWgBits.SelectedIndex = 1;
            cmbWgOrder.SelectedIndex = 0;
            cmbWgType.SelectedIndex = 0;
            cmbRepeatUse.SelectedIndex = 0;
            cmbRepeatMode.SelectedIndex = 0;
            numRepeatInterval.Value = 3;
            cmbBrightness.SelectedIndex = 0;
            cmbExposure.SelectedIndex = 0;
            cmbIR.SelectedIndex = 0;
            cmbLight.SelectedIndex = 0;
            cmbBioassay.SelectedIndex = 0;
            cmbDistance.SelectedIndex = 0;
            cmbFaceMask.SelectedIndex = 0;
            cmbBodyTmpUse.SelectedIndex = 0;
            cmbBodyTmpFromat.SelectedIndex = 0;
            cmbBodyTmpShow.SelectedIndex = 0;
            cmbTimeGroup.Items.Clear();
            for (int i = 0; i < 64; i++)
            {
                cmbTimeGroup.Items.Add(i + 1);
            }
            cmbTimeGroup.SelectedIndex = 0;
            cmbWeekGroup.SelectedIndex = 0;
            cmbDoor.SelectedIndex = 0;
            cmbLanguage.SelectedIndex = 0;
            cmbSavePhoto.SelectedIndex = 0;
            cmbSaveExternalvisitors.SelectedIndex = 0;
            cmbVolume.SelectedIndex = 0;
            cmbVoiceMode.SelectedIndex = 0;
            cmbGrettings.SelectedIndex = 0;
            cmbStrangerVoice.SelectedIndex = 0;
            cmbOpenTimeoutAlarmUse.SelectedIndex = 0;
            cmbOpenTimeoutAlarmAlarm.SelectedIndex = 0;
            cmbSensorAlarmUse.SelectedIndex = 0;
            cmbSensorAlarmTime.SelectedIndex = 0;
            cmbDhcp.SelectedIndex = 0;
            cmbSsl.SelectedIndex = 0;
            cmbStatus.SelectedIndex = 0;
            cmbWifiUse.SelectedIndex = 0;
        }

        Dictionary<int, Models.GroupDetail> TimeGroup = new Dictionary<int, Models.GroupDetail>();
        private void cmbTimeGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!TimeGroup.ContainsKey(cmbTimeGroup.SelectedIndex))
            {
                TimeGroup.Add(cmbTimeGroup.SelectedIndex, new Models.GroupDetail
                {
                    Num = cmbTimeGroup.SelectedIndex,
                    Time = new Models.WeekModel()
                });
            }
            cmbWeekGroup.SelectedIndex = 0;
        }
        private void cmbWeekGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            var groupDetail = TimeGroup[cmbTimeGroup.SelectedIndex];
            if (groupDetail != null)
            {
                string week;
                switch (cmbWeekGroup.SelectedIndex)
                {
                    case 0:
                        week = groupDetail.Time.Week1;
                        break;
                    case 1:
                        week = groupDetail.Time.Week2;
                        break;
                    case 2:
                        week = groupDetail.Time.Week3;
                        break;
                    case 3:
                        week = groupDetail.Time.Week4;
                        break;
                    case 4:
                        week = groupDetail.Time.Week5;
                        break;
                    case 5:
                        week = groupDetail.Time.Week6;
                        break;
                    case 6:
                        week = groupDetail.Time.Week7;
                        break;
                    default:
                        week = string.Empty;
                        break;
                }

                SetAllTimePicker(groupBox25, "dateStart", "dateEnd", week);

            }
        }

        private void GetTimeGroupWeek(Models.WeekModel week)
        {
            string bigenName = "dateStart";
            string endName = "dateEnd";
            switch (cmbWeekGroup.SelectedIndex)
            {
                case 0:
                    week.Week1 = GetAllTimePicKer(groupBox25, bigenName, endName);
                    break;
                case 1:
                    week.Week2 = GetAllTimePicKer(groupBox25, bigenName, endName);
                    break;
                case 2:
                    week.Week3 = GetAllTimePicKer(groupBox25, bigenName, endName);
                    break;
                case 3:
                    week.Week4 = GetAllTimePicKer(groupBox25, bigenName, endName);
                    break;
                case 4:
                    week.Week5 = GetAllTimePicKer(groupBox25, bigenName, endName);
                    break;
                case 5:
                    week.Week6 = GetAllTimePicKer(groupBox25, bigenName, endName);
                    break;
                case 6:
                    week.Week7 = GetAllTimePicKer(groupBox25, bigenName, endName);
                    break;
                default:
                    break;
            }
        }
        private void btnSaveTimeGroup_Click(object sender, EventArgs e)
        {
            var groupDetail = TimeGroup[cmbTimeGroup.SelectedIndex];
            GetTimeGroupWeek(groupDetail.Time);
        }
        Models.WeekModel SensorAlarmWeek;
        private void btnSaveSensorAlarmWeek_Click(object sender, EventArgs e)
        {
            if (SensorAlarmWeek == null)
            {
                SensorAlarmWeek = new Models.WeekModel();
            }
            GetSensorAlarmWeek(SensorAlarmWeek);

        }
        private void GetSensorAlarmWeek(Models.WeekModel week)
        {
            string bigenName = "dateSensorAlarmStart";
            string endName = "dateSensorAlarmEnd";
            switch (cmbSensorAlarmTime.SelectedIndex)
            {
                case 0:
                    week.Week1 = GetAllTimePicKer(groupBox6, bigenName, endName);
                    break;
                case 1:
                    week.Week2 = GetAllTimePicKer(groupBox6, bigenName, endName);
                    break;
                case 2:
                    week.Week3 = GetAllTimePicKer(groupBox6, bigenName, endName);
                    break;
                case 3:
                    week.Week4 = GetAllTimePicKer(groupBox6, bigenName, endName);
                    break;
                case 4:
                    week.Week5 = GetAllTimePicKer(groupBox6, bigenName, endName);
                    break;
                case 5:
                    week.Week6 = GetAllTimePicKer(groupBox6, bigenName, endName);
                    break;
                case 6:
                    week.Week7 = GetAllTimePicKer(groupBox6, bigenName, endName);
                    break;
                default:
                    break;
            }
        }
    }
}
